/**
 * 在background主进程中调用grpc代码, 待preload预加载脚本通信
 */
const { ipcMain, session } = require('electron');
var google_protobuf_empty_pb = require('google-protobuf/google/protobuf/empty_pb.js')
var google_protobuf_wrappers_pb = require('google-protobuf/google/protobuf/wrappers_pb.js');
const { NewUploadItem, UploadItemTransInfo, PauseUploadInfo, PauseMethodMsg, TransSetting } = require('../grpc/Upload_pb')
// 导入 Node.js 服务代码
const grpcService = require('../api/grpcClient')
const { ListArray } = require('./components/UtilsMethod')
const { readConfigFile } = require('../utils/getBaseUrl')
const { signature, getUserName } = require("../utils/encrypt")
const store = require("../electronStore/index")

const config = readConfigFile()
// 传输http基地址
ipcMain.handle('httpBaseUrl', () => {
  return config.http_baseUrl
})
// 加密请求头，防止登录过期
ipcMain.handle("getEncrypt", () => {
  return signature()
})

// 获取 userName
ipcMain.handle("getUserName", (event, userName) => {
  store.set("userName", userName)
  getUserName(userName)
  return
})
// 获取上传列表
ipcMain.handle('getUploadList', async () => {
  try {
    const request = new google_protobuf_empty_pb.Empty()
    const response = await grpcService.getUploadList(request)
    console.log('buffer', response)
    // return response.toObject()
    return ListArray(response)
  } catch (error) {
    console.log('error', error)
  }
})
// 获取上传完成列表
ipcMain.handle('getFinishUploadList', async () => {
  try {
    const request = new google_protobuf_empty_pb.Empty()
    const response = await grpcService.getFinishUploadList(request)

    return ListArray(response)
  } catch (error) {
    return error
  }
})
// 上传文件
ipcMain.handle('addUpload', async (event, params) => {
  try {
    console.log('params', params)
    const request = new NewUploadItem()
    const baseInfo = new UploadItemTransInfo()

    baseInfo.setSrcpath(params.srcpath) // string
    baseInfo.setDestdir(params.destdir) // string
    baseInfo.setDestname(params.destname) // string
    /**
     * 
     * @param {number} 0: 跳过文件，如果目标文件已存在
     * @param {number} 1: 仅当目标文件存在且大小相同时才跳过文件
     * @param {number} 2: 覆盖目标文件，如果目标文件已存在
     * @param {number} 3: 在目标文件末尾追加数据，如果目标文件已存在
     */
    baseInfo.setCheckdestmethod(params.checkDestMethod)
    baseInfo.setMd5(params.md5) // 布尔值 此处传true
    baseInfo.setDestserver(params.destServer) // string
    /**
     * @param {number} 0: 数据传输方式
     * @param {number} 1: 分块（Chunk）数据传输方式
     */
    baseInfo.setTransmethod(params.transMethod)
    // 优先级：number ==> P_DEFAULT: 0, P_LOW: 1, P_MID: 5, P_HEIGHT: 9
    baseInfo.setPriority(params.priority)

    request.setTransinfo(baseInfo)
    const response = await grpcService.addUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    return List
  } catch (error) {
    console.log('error', error)
    return error
  }
})
// 暂停上传
ipcMain.handle('pauseUpload', async (event, params) => {
  try {
    const request = new PauseUploadInfo()
    request.setItemid(params.itemID)
    request.setMethod(params.method) // 0/1
    console.log('暂停上传', request)
    const response = await grpcService.pauseUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    return List
  } catch (error) {
    return error
  }
})
// 恢复上传
ipcMain.handle('resumeUpload', async (event, params) => {
  try {
    const request = new google_protobuf_wrappers_pb.StringValue()
    request.setValue(params)
    console.log('恢复上传', request)
    const response = await grpcService.resumeUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    console.log(List)
    return List
  } catch (error) {
    return error
  }
})
// 移除上传
ipcMain.handle('deleteUpload', async (event, params) => {
  try {
    const request = new google_protobuf_wrappers_pb.StringValue()
    request.setValue(params)
    const response = await grpcService.deleteUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    return List
  } catch (error) {
    return error
  }
})
// 根据id获取状态
ipcMain.handle('getStateByID', async (event, params) => {
  try {
    const request = new google_protobuf_wrappers_pb.StringValue()
    request.setValue(params)
    console.log('根据id获取状态', request)
    const response = await grpcService.getStateByID(request)
    const List = {
      /**
       * @param {number} 0: 无状态
       * @param {number} 1: 等待中(任务在排队)
       * @param {number} 2: 任务正在运行
       * @param {number} 3: 任务已完成
       * @param {number} 4: 任务发生错误
       * @param {number} 5: 任务已暂停
       * @param {number} 6: 任务已停止
       */
      state: response.getState(),
      transRage: response.getTransrage()
    }

    return List
  } catch (error) {
    return error
  }
})
// 删除全部上传
ipcMain.handle('deleteAllUpload', async () => {
  try {
    const request = new google_protobuf_empty_pb.Empty()
    const response = await grpcService.deleteAllUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    return List
  } catch (error) {
    return error
  }
})
// 暂停全部上传
ipcMain.handle('pauseAllUpload', async (event, params) => {
  try {
    console.log('params', params)
    const request = new PauseMethodMsg()
    request.setMethod(params) // 0/1
    console.log('暂停全部上传', request)
    const response = await grpcService.pauseAllUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }

    return List
  } catch (error) {
    return error
  }
})
// 恢复全部上传
ipcMain.handle('resumeAllUpload', async () => {
  try {
    const request = new google_protobuf_empty_pb.Empty()
    const response = await grpcService.resumeAllUpload(request)
    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }

    return List
  } catch (error) {
    return error
  }
})
// 设置传输设置
ipcMain.handle('setTransSetting', async (event, params) => {
  try {
    const request = new TransSetting()
    request.setDownloadconcurrentcount(params.downloadconcurrentcount)
    request.setDownloadtransrate(params.downloadtransrate)
    request.setDownloaddir(params.downloaddir)
    request.setUploadconcurrentcount(params.uploadconcurrentcount)
    request.setUploadtransrate(params.uploadtransrate)
    console.log('设置', request)
    const response = await grpcService.setTransSetting(request)

    const List = {
      code: response.getCode(),
      message: response.getMessage()
    }
    return List
  } catch (error) {
    return error
  }
})
// 获取传输设置
ipcMain.handle('getTransSetting', async () => {
  try {
    const request = new google_protobuf_empty_pb.Empty()
    const response = await grpcService.getTransSetting(request)
    console.log('设置', response)
    const List = response.toObject()
    return List
  } catch (error) {
    console.log('error', error)
    return error
  }
})
